import {
  Button,
  message,
  Form,
  FormInstance,
  Row,
  Col
} from 'antd';
import { useRequest } from 'ahooks';
import { useCallback, useEffect, useState } from 'react';
import { useParams, useHistory } from 'react-router-dom';

import BasicInfo from './basic-info';
import AnswerShow from './answer';
import {
  WorkUnit,
  Affiliated,
  JobPosition,
  OperatingPost,
  Name,
  Num
} from './basic-info/item';

import * as APIS from '../../constants/api-constants';

/**
 * 创建用户基本信息可选组件数组
 */
const createComponentArr = (
  userNameVisible: boolean,
  userNumVisible: boolean,
  workUnitVisible: boolean,
  affiliatedVisible: boolean,
  jobPositionVisible: boolean,
  operatingPostVisible: boolean,
  workUnit: AnswerSetting.SelectOption[],
  affiliatedUnit: AnswerSetting.SelectOption[],
  jobPosition: AnswerSetting.SelectOption[],
  operatingPost: AnswerSetting.SelectOption[],
  form: FormInstance<any>
) => {
  // 创建可选项数组
  const optionnalComponent: JSX.Element[] = [];
  if (userNameVisible) {
    optionnalComponent.push(
      <Name form={form} />
    );
  }

  if (userNumVisible) {
    optionnalComponent.push(
      <Num form={form} />
    );
  }

  if (workUnitVisible) {
    optionnalComponent.push(
      <WorkUnit workUnit={workUnit} form={form} />
    );
  }

  if (affiliatedVisible) {
    optionnalComponent.push(
      <Affiliated affiliatedUnit={affiliatedUnit} form={form} />
    );
  }

  if (jobPositionVisible) {
    optionnalComponent.push(
      <JobPosition jobPosition={jobPosition} form={form} />
    );
  }

  if (operatingPostVisible) {
    optionnalComponent.push(
      <OperatingPost operatingPost={operatingPost} form={form} />
    );
  }
  return optionnalComponent;
};

/**
 * 创建用户基本信息请求参数
 */
const createSaveParam = (
  userNameVisible: boolean,
  userNumVisible: boolean,
  workUnitVisible: boolean,
  affiliatedVisible: boolean,
  jobPositionVisible: boolean,
  operatingPostVisible: boolean,
  basicInfo: AnswerSetting.UserBasicInitInfo
) => {
  const {
    tel,
    name,
    num,
    gender,
    maritalStatus,
    childrenSituation,
    age,
    education,
    workUnit,
    affiliated,
    jobPosition,
    operatingPost,
    email
  } = basicInfo;

  const userBasicParam: AnswerSetting.UserBasicParamType = {
    tel,
    name,
    num,
    gender,
    maritalStatus,
    childrenSituation,
    age,
    education,
    email
  };

  if (userNameVisible) {
    userBasicParam.name = name;
  }

  if (userNumVisible) {
    userBasicParam.num = num;
  }

  if (workUnitVisible) {
    userBasicParam.workUnit = workUnit;
  }

  if (affiliatedVisible) {
    userBasicParam.affiliated = affiliated;
  }

  if (jobPositionVisible) {
    userBasicParam.jobPosition = jobPosition;
  }

  if (operatingPostVisible) {
    userBasicParam.operatingPost = operatingPost;
  }
  return userBasicParam;
};

export default () => {
  const history = useHistory();
  const [basicInfoForm] = Form.useForm();
  const [scoreForm] = Form.useForm();
  const [optionnalComponent, setOptionnalComponent] = useState<JSX.Element[]>();
  const [basicInfo, setBasicInfo] = useState<AnswerSetting.UserBasicInitInfo>();
  const [isModify, setIsModify] = useState(false);
  const [scoreArr, setScoreArr] = useState<number[]>([]);
  const [
    questionnaireBasicInfo,
    setQuestionnaireBasicInfo
  ] = useState<AnswerSetting.QuestionnaireBaiscInit>();
  const {
    mergeUuid,
    questionnaireUuid: selectedQuestionanireUuid,
    templateTitle,
    questionnaireName
  } = useParams<{
    mergeUuid: string | undefined,
    questionnaireUuid: string | undefined,
    templateTitle: string | undefined,
    questionnaireName: string | undefined
  }>();
  const [
    questionnaireUuid,
    setQuestionnaireUuid
  ] = useState(selectedQuestionanireUuid);

  /** 获取当前 mergeUuid 对应的回答基本信息 */
  const {
    run: requestAnswerInfo
  } = useRequest((currentMergeUuid: string) => ({
    url: APIS.ANSWER_INFO,
    method: 'GET',
    params: {
      mergeUuid: currentMergeUuid
    }
  }), {
    manual: true,
    onSuccess: (result) => {
      const currentAnswerInfo = result.data;
      const {
        tel,
        name,
        num,
        gender,
        maritalStatus,
        childrenSituation,
        age,
        education,
        workUnit,
        affiliated,
        jobPosition,
        operatingPost,
        email
      } = currentAnswerInfo;
      const userBasicInfo: AnswerSetting.UserBasicInitInfo = {
        templateTitle,
        questionnaireName,
        name,
        num,
        tel,
        gender,
        maritalStatus,
        childrenSituation,
        age,
        education,
        email,
        workUnit: workUnit?.name,
        affiliated: affiliated?.name,
        jobPosition: jobPosition?.name,
        operatingPost: operatingPost?.name
      };
      setBasicInfo(userBasicInfo);
    },
    onError: () => {
      message.error('用户已回答信息获取错误');
    },
  });

  /** 获取当前 mergeUuid 对应的 scoreList */
  const {
    run: requestScoreList,
    loading: requestScoreListLoading
  } = useRequest((currentMergeUuid: string) => ({
    url: APIS.ANSWER_SCORE_LIST,
    method: 'GET',
    params: {
      mergeUuid: currentMergeUuid
    }
  }), {
    manual: true,
    onSuccess: (result) => {
      const { data } = result;
      data.forEach((scoreItem: number, index: number) => {
        scoreForm.setFieldsValue({ [`score${index}`]: scoreItem });
      });
      setScoreArr(data);
    },
    onError: () => {
      message.error('用户分数获取错误');
    },
  });

  /**
  * 获取 questionnaireUuid 对应的 questionnaire
  */
  const { run: requestQuestionnaire } = useRequest((uuid) => ({
    url: APIS.QUESTIONNAIRE_MANAGER_DETAIL,
    method: 'GET',
    params: { uuid }
  }), {
    manual: true,
    onSuccess: (res) => {
      const questionnaireBasic: AnswerSetting.QuestionnaireBaiscInit = res.data;
      setQuestionnaireBasicInfo(questionnaireBasic);
      // 生成可选组件数组
      const {
        userNameVisible,
        userNumVisible,
        workUnitVisible,
        affiliatedVisible,
        jobPositionVisible,
        operatingPostVisible,
        workUnit,
        affiliatedUnit,
        jobPosition,
        operatingPost
      } = questionnaireBasic;
      setOptionnalComponent(createComponentArr(
        userNameVisible,
        userNumVisible,
        workUnitVisible,
        affiliatedVisible,
        jobPositionVisible,
        operatingPostVisible,
        workUnit,
        affiliatedUnit,
        jobPosition,
        operatingPost,
        basicInfoForm
      ));
    }
  });

  /** 保存用户手动录入信息 */
  const {
    run: saveEnterManually,
    loading
  } = useRequest((
    currentBasicInfo: AnswerSetting.UserBasicInitInfo,
    currentQuestionnaireBasicInfo: AnswerSetting.QuestionnaireBaiscInit
  ) => {
    const {
      userNameVisible,
      userNumVisible,
      workUnitVisible,
      affiliatedVisible,
      jobPositionVisible,
      operatingPostVisible,
    } = currentQuestionnaireBasicInfo;
    // 生成用户基本信息请求参数
    const userBasicInfoParams = createSaveParam(
      userNameVisible,
      userNumVisible,
      workUnitVisible,
      affiliatedVisible,
      jobPositionVisible,
      operatingPostVisible,
      currentBasicInfo
    );
    return {
      url: APIS.ANSWER_MANUAL_OPERATION,
      method: 'POST',
      data: {
        questionnaireUuid,
        mergeUuid,
        ...userBasicInfoParams,
        score: scoreArr,
      }
    };
  }, {
    manual: true,
    onSuccess: () => {
      if (mergeUuid) {
        history.push('/home/answerList/');
        return;
      }
      history.push('/home/answerSetting/success');
    },
    onError: () => {
      message.error('保存失败');
    },
  });

  useEffect(() => {
    if (mergeUuid) {
      Promise.all([
        requestScoreList(mergeUuid),
        requestAnswerInfo(mergeUuid)
      ]);
      setIsModify(true);
    }
  }, [mergeUuid]);

  const handleQuestionnaireChange = useCallback((uuid: string) => {
    requestQuestionnaire(uuid);
  }, []);

  useEffect(() => {
    if (questionnaireUuid) {
      handleQuestionnaireChange(questionnaireUuid);
    }
  }, [questionnaireUuid]);

  const handleSave = async () => {
    const [basicInfoResult, scoreResult] = await Promise.allSettled([
      basicInfoForm.validateFields(),
      scoreForm.validateFields()
    ]);

    if (basicInfoResult.status === 'fulfilled'
      && scoreResult.status === 'fulfilled'
    ) {
      const userBasicInfoData = basicInfoForm.getFieldsValue();

      if (userBasicInfoData && questionnaireBasicInfo) {
        saveEnterManually(userBasicInfoData, questionnaireBasicInfo);
      }
    }
  };
  return (
    <>
      <BasicInfo
        form={basicInfoForm}
        isModify={isModify}
        basicInfo={basicInfo}
        templateTitle={templateTitle}
        questionnaireName={questionnaireName}
        optionnalComponent={optionnalComponent}
        setQuestionnaireUuid={setQuestionnaireUuid}
      />
      <AnswerShow
        form={scoreForm}
        scoreArr={scoreArr}
        setScoreArr={setScoreArr}
        requestScoreListLoading={requestScoreListLoading}
      />
      <Row>
        <Col offset={16}>
          <Button
            type="primary"
            loading={loading}
            onClick={handleSave}
          >
            保存
          </Button>
        </Col>
      </Row>
    </>
  );
};
